import axios from 'axios';
import config from './config';
import Cookies from "js-cookie";
import router from '@/router';
import store from '@/store';
import {Message} from 'element-ui';

export default function $axios(options) {
    return new Promise((resolve, reject) => {

        const instance = axios.create({
            baseURL: config.baseUrl,
            headers: config.headers,
            timeout: config.timeout,
            withCredentials: config.withCredentials
        });

        // request 请求拦截器
        instance.interceptors.request.use(
                //请求信息
                config => {
                    // 发送请求时携带token
                    config.headers.token = Cookies.get('token');
                    // 携带地址信息
                    let currentPosition = store.state.map.currentAddress;
                    let headerCurrentAddress = {
                        lng:currentPosition.lng,
                        lat:currentPosition.lat,
                        addressDetail:currentPosition.addressDetail,
                    };
                    config.headers.currentPosition = escape(JSON.stringify(headerCurrentAddress || '{}'));
                    return config
                },
                // 请求发生错误时
                error => {
                    // 判断请求超时
                    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
                        console.log('timeout请求超时')
                        router.push({
                            path: `/error/timeout`
                        })
                    }
                    // 需要重定向到错误页面
                    const errorInfo = error.response;
                    if (errorInfo) {
                        error = errorInfo.data;  // 页面那边catch的时候就能拿到详细的错误信息,看最下边的Promise.reject
                        const errorStatus = errorInfo.status; // 404 403 500 ...
                        router.push({
                            path: `/error/${errorStatus}`
                        })
                    }
                    return Promise.reject(error); // 在调用的那边可以拿到(catch)你想返回的错误信息
                }
        );

        // response 响应拦截器
        instance.interceptors.response.use(
                response => {
                    //自定义异常后续自己管控
                    if (response.data.code != 0) {
                        return Promise.reject(response.data);
                    }
                    return response.data
                },
                //系统级异常直接管控
                err => {
                    if (err && err.response) {
                        switch (err.response.status) {
                            case 400:
                                err.msg = '请求错误'
                                break
                            case 401:
                                err.msg = '未授权，请登录'
                                break
                            case 403:
                                err.msg = '拒绝访问';
                                break
                            case 404:
                                err.msg = `请求地址出错: ${err.response.config.url}`
                                break
                            case 408:
                                err.msg = '请求超时'
                                break
                            case 500:
                                err.msg = '服务器内部错误'
                                break
                            case 501:
                                err.msg = '服务未实现'
                                break
                            case 502:
                                err.msg = '网关错误'
                                break
                            case 503:
                                err.msg = '服务不可用'
                                break
                            case 504:
                                err.msg = '网关超时'
                                break
                            case 505:
                                err.msg = 'HTTP版本不受支持'
                                break
                            default:
                                err.msg = '未知错误！错误代码：' + err.response.status
                        }
                    } else {
                        err.code = 'netError';
                        err.msg = '无法连接服务';
                    }
                    return Promise.reject(err) // 返回接口返回的错误信息
                }
        );

        // 请求处理
        instance(options).then(res => {
            resolve(res);
            return false
        }).catch(errorData => {
            // Message.error(error.message);
            console.log(errorData.msg);
            let code = errorData.code;
            if(!isNaN(code) && code < 1000) {
                router.push({
                    path: `/error/xxx`,
                    query: {
                        code: code,
                        message: errorData.msg,
                    },
                });
            }
            if(code == 'netError'){
                router.push({
                    path: `/error/errorNet`
                })
            }
            //所有异常通过 then方法 - code判定，不走catch 异常拦截；方法异常拦截通过全局上面已处理。
            resolve(errorData);
            // reject(errorData)
        });

    });


}
